package com.kun.demo04_synchronize.probelm;


import org.junit.Test;

//银行取钱问题，多线程情况下，线程不安全
public class NotSafeCase2_goBank {

    class Bank{
        int money;

        public Bank(int money) {
            this.money = money;
        }
    }

    class Customer implements Runnable{
        int amount;//取钱数目
        Bank bank;

        public Customer(int amount, Bank bank) {
            this.amount = amount;
            this.bank = bank;
        }


        @Override
        public void run() {
            if(bank.money < amount){
                return;
            }

            //模拟延迟
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //取钱
            System.out.println(Thread.currentThread().getName() + "取钱" + amount + "元");
            bank.money = bank.money - amount;
            System.out.println(Thread.currentThread().getName() + "取钱成功，当前余额为：" +  bank.money);
        }
    }



    @Test
    public void test() throws InterruptedException {
        Bank bank = new Bank(100);
        new Thread(new Customer(100, bank), "A").start(); // 线程A取100元
        new Thread(new Customer(50, bank), "B").start(); // 线程B取50元
        Thread.sleep(3000); // 延迟主线程退出
    }
}


